// SignalR.js
import * as signalR from '@microsoft/signalr'

class SignalRService {
  constructor() {
    this.connection = null
    this.isConnected = false
  }

  async connect(currentUser) {
    try {
      // 如果已有连接，先断开
      if (this.connection) {
        await this.disconnect()
      }

      // 使用正确的后端地址
      const baseUrl = 'http://localhost:5006'
      
      console.log(`尝试连接到 SignalR: ${baseUrl}/connectHub`)

      this.connection = new signalR.HubConnectionBuilder()
        .withUrl(`${baseUrl}/connectHub`, {
          // 如果后端需要认证，取消注释下面这行
          // accessTokenFactory: () => currentUser.username,
          skipNegotiation: true, // 对于 WebSocket 可以设为 true
          transport: signalR.HttpTransportType.WebSockets
        })
        .withAutomaticReconnect([0, 2000, 5000, 10000, 15000]) // 重连策略
        .configureLogging(signalR.LogLevel.Information)
        .build()

      // 设置事件处理器
      this.setupEventHandlers()

      // 启动连接
      await this.connection.start()
      
      console.log('✅ SignalR 连接成功')
      this.isConnected = true
      this.notifyConnectionStatus('connected')
      
      // 注册用户
      await this.registerUser(currentUser.username)
      
      return true
      
    } catch (error) {
      console.error('❌ SignalR 连接失败:', error)
      this.isConnected = false
      this.notifyConnectionStatus('error')
      this.notifyError(error.message)
      return false
    }
  }

  setupEventHandlers() {
    if (!this.connection) return

    // 接收消息
    this.connection.on('ReceiveMessage', (sender, message) => {
      console.log('📨 收到消息:', sender, message)
      if (this.handleReceiveMessage) {
        this.handleReceiveMessage(sender, message)
      }
    })

    // 用户加入
    this.connection.on('UserJoined', (username) => {
      console.log('👤 用户加入:', username)
      if (this.handleUserStatus) {
        this.handleUserStatus(username, true)
      }
    })

    // 用户离开
    this.connection.on('UserLeft', (username) => {
      console.log('🚪 用户离开:', username)
      if (this.handleUserStatus) {
        this.handleUserStatus(username, false)
      }
    })

    // 在线用户列表
    this.connection.on('OnlineUsers', (users) => {
      console.log('📊 在线用户列表:', users)
      if (this.handleOnlineUsers) {
        this.handleOnlineUsers(users)
      }
    })

    // 连接状态监听
    this.connection.onreconnecting((error) => {
      console.log('🔄 SignalR 重新连接中...', error)
      this.isConnected = false
      this.notifyConnectionStatus('reconnecting')
    })

    this.connection.onreconnected((connectionId) => {
      console.log('✅ SignalR 重新连接成功')
      this.isConnected = true
      this.notifyConnectionStatus('connected')
    })

    this.connection.onclose((error) => {
      console.log('❌ SignalR 连接关闭', error)
      this.isConnected = false
      this.notifyConnectionStatus('disconnected')
    })
  }

  async registerUser(username) {
    if (this.connection && this.isConnected) {
      try {
        await this.connection.invoke('RegisterUser', username)
        console.log('✅ 用户注册成功:', username)
        
        // 获取在线用户列表
        await this.getOnlineUsers()
      } catch (error) {
        console.error('❌ 用户注册失败:', error)
      }
    }
  }

  async sendMessage(receiver, message) {
    if (!this.connection || !this.isConnected) {
      throw new Error('未连接到服务器')
    }

    try {
      await this.connection.invoke('SendMessage', receiver, message)
      console.log('✅ 消息发送成功:', receiver, message)
      return true
    } catch (error) {
      console.error('❌ 消息发送失败:', error)
      throw error
    }
  }

  async getOnlineUsers() {
    if (!this.connection || !this.isConnected) {
      return []
    }

    try {
      const users = await this.connection.invoke('GetOnlineUsers')
      console.log('📋 获取在线用户:', users)
      return users || []
    } catch (error) {
      console.error('❌ 获取在线用户失败:', error)
      // 如果后端没有这个方法，静默失败
      return []
    }
  }

  async disconnect() {
    if (this.connection) {
      try {
        await this.connection.stop()
        console.log('🔌 SignalR 连接已断开')
      } catch (error) {
        console.error('断开连接时出错:', error)
      } finally {
        this.connection = null
        this.isConnected = false
      }
    }
  }

  notifyConnectionStatus(status) {
    if (this.handleConnectionStatus) {
      this.handleConnectionStatus(status)
    }
  }

  notifyError(error) {
    if (this.handleError) {
      this.handleError(error)
    }
  }
}

// 创建单例实例
const signalRService = new SignalRService()
export default signalRService